package com.fuful.servlet;

import com.fuful.domain.Product;
import com.fuful.service.ProductService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class FindProductAction extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         * 1.获得请求参数值
         * 2.调用业务逻辑
         * 3.获得结果
         * 4.根据结果判断是否需要共享对象(session/request)
         * 5.转发或重定向
         */
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");


        ProductService ps = new ProductService();


        /**
         * 处理异步请求
         * 前端传来method参数
         * servlet从数据库查询数据
         * 返回json数据，拼出来的json字符串
         * */
        String method = request.getParameter("method");
        if (method != null){
            if(method.equals("querySome")){
                String jsonStr = "";
                int  position = Integer.parseInt(request.getParameter("position"));
                List<Product> data =  ps.findSome(position,3);
                for(Product product : data){
                    jsonStr += "<tr><td>" + product.getPcode() +
                            "</td><td>" + product.getPname() +
                            "</td><td>" + product.getPtid().getPtname() +
                            "</td><td>" + product.getPprice() +
                            "</td><td>x x x</td></tr>";
                }
                PrintWriter out = response.getWriter();
                out.print(jsonStr);
                out.flush();
                out.close();


                return;
            }
        }

        List<Product> data =  ps.findSome(0,3);

        //session共享
        HttpSession session = request.getSession();
        //共享
        session.setAttribute("productdata",data);
        response.sendRedirect("products.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}

